/**
 *  Copyright (C) 2008-2013  Telosys project org. ( http://www.telosys.org/ )
 *
 *  Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *          http://www.gnu.org/licenses/lgpl.html
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.telosys.persistence.dao;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import org.telosys.common.TelosysRuntimeException;
import org.telosys.persistence.mapping.AttributeMapping;
import org.telosys.util.introspection.BeanIntrospector;

/**
 * Provider for field mappers
 * 
 * @author Laurent Guerin
 *
 */
public class FieldMapperProvider {

	private final static Map<String,FieldMapper> allFieldMappers = new HashMap<String,FieldMapper>();
			
	public final static FieldMapper get(Class<?> entityClass, int index, AttributeMapping mappingDefinition ) 
	{
		if ( null == entityClass ) throw new IllegalArgumentException("Class is null");

		String fieldName = mappingDefinition.getAttributeName();
		String sKey = entityClass.getName() + "-" +  fieldName  ;
		
		//--- Is there a FieldMapper already created for this entity-field ?
		FieldMapper fieldMapper = allFieldMappers.get(sKey);
		if ( fieldMapper != null ) 
		{
			//--- Found 
			return fieldMapper ;
		}
		else 
		{
			//--- Not found 
			
			//--- Create the field mapper 
			
			Field field = null ;
			try {
				field = BeanIntrospector.getFieldByName(entityClass, fieldName);
			} catch (SecurityException e) {
				throw new TelosysRuntimeException("Cannot get field '" + fieldName + "' in class (SecurityException)" + entityClass.getName(), e);
			} catch (NoSuchFieldException e) {
				throw new TelosysRuntimeException("Cannot get field '" + fieldName + "' in class (NoSuchFieldException)" + entityClass.getName(), e);
			}
			
			if ( ! field.isAccessible() ) {
				field.setAccessible(true);
			}
			
			SpecializedFieldMapper specializedFieldMapper = SpecializedFieldMapperProvider.getMapperForType( field.getType(), mappingDefinition.getComplement() ) ;

			//fieldMapper = new FieldMapper ( entityClass, index, mappingDefinition, specializedFieldMapper );
			fieldMapper = new FieldMapper ( entityClass, field, mappingDefinition, specializedFieldMapper );
			
			//--- Store it for the next times
			allFieldMappers.put(sKey, fieldMapper);
			
			return fieldMapper ;
		}
		
	}

}
